package xhwl.hmo.mall.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import xhwl.hmo.mall.IntentConstants;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.adapter.AllOrderAdapter;
import xhwl.hmo.mall.event.OrderStateChangeEvent;
import xhwl.hmo.mall.http.api.CancelOrderApi;
import xhwl.hmo.mall.http.api.OrderListApi;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.http.bean.resp.OrderListBean;
import xhwl.hmo.mall.utils.AlarmUtil;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.pulltorefresh.PullToRefreshRecyclerView;
import xhwl.pulltorefresh.callback.PullToRefreshListener;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * 我的订单待付款
 */

public class PayWaitingFragment extends BaseFragment implements PullToRefreshListener, AllOrderAdapter.Callback {
    private PullToRefreshRecyclerView mRecyclerView;
    AllOrderAdapter adapter;
    ArrayList<OrderListBean> mList = new ArrayList<>();
    private int mPage = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_all_order, null);
        return view;
    }

    @Override
    protected void initView(View view) {
        mRecyclerView = (PullToRefreshRecyclerView) view.findViewById(R.id.recyclerView);
    }

    @Override
    protected void processOper() {
        super.processOper();
        initRecylerView();
        adapter = new AllOrderAdapter(getActivity(), mList,this);
    }

    @Override
    protected void initListener() {
        mRecyclerView.setPullToRefreshListener(this);
    }

    @Override
    protected void loadData() {
        mRecyclerView.getRefreshLayout().autoRefresh();
    }

    private void getOrderList(final int page_num) {
        /**
         //order_status 订单状态 0 -- 待付款 1--已付款 2--已退款 3--支付失败 4--消费成功
         //fh_status 发货状态 9表示已完成
         //comment_status评价状态 0 -- 未评价  1 -- 已评价
         * when c.fh_status = '0' then
         '未发货'
         when c.fh_status = '1' then
         '无需发货'
         when c.fh_status = '2' then
         '已发货'
         when c.fh_status = '3' then
         '确认收货'
         */
        OrderListApi api = new OrderListApi(page_num, "0", "", "");
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<ArrayList<OrderListBean>>>() {
            @Override
            public void onNext(HttpResp<ArrayList<OrderListBean>> resp) {
                if (page_num == 1) {
                    if (resp != null) {
                        mRecyclerView.setRefreshComplete();
                        mPage = 1;
                        mList.clear();
                        if ( resp.data != null && resp.data.size() > 0) {
                            mList.addAll(resp.data);
                        }
                        mRecyclerView.setAdapter(adapter);
                    } else {
                        mRecyclerView.setRefreshFail();
                    }
                } else {
                    if (resp != null) {
                        mRecyclerView.setLoadMoreComplete();
                        if ( resp.data != null && resp.data.size() > 0) {
                            mPage = page_num;
                            mList.addAll(resp.data);
                            adapter.notifyDataSetChanged();
                        } else {
                            mRecyclerView.setLoadMoreFail();
                        }
                    }
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                if (page_num == 1) {
                    mRecyclerView.setRefreshFail();
                } else {
                    mRecyclerView.setLoadMoreFail();
                }
            }
        });
    }

    private void initRecylerView() {
        //设置EmptyView
        View emptyView = View.inflate(getActivity(), R.layout.layout_empty_view, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        ImageView background = (ImageView) emptyView.findViewById(R.id.nodata);
        background.setImageResource(R.drawable.no_order);
        mRecyclerView.setEmptyView(emptyView);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView mRecyclerView, int dx, int dy) {
                super.onScrolled(mRecyclerView, dx, dy);


            }
        });
        //设置是否开启上拉加载
        mRecyclerView.setLoadingMoreEnabled(true);
        //设置是否开启下拉刷新
        mRecyclerView.setPullRefreshEnabled(true);
        //设置是否显示上次刷新的时间
        mRecyclerView.displayLastRefreshTime(true);
    }

    @Override
    public void onRefresh() {
        //加载订单数据
        getOrderList(1);
    }

    @Override
    public void onLoadMore() {
        getOrderList(mPage + 1);
    }

    @Override
    public void click(View v) {
        switch (v.getId()) {
            case R.id.order_cancel:
                Log.e("=====", "order_cancel");
                OrderListBean orderListBean = (OrderListBean) v.getTag();
                Log.e("=====getORDER_ID()", orderListBean.getORDER_ID());
                cancelOrder(orderListBean.getORDER_ID());
                break;
            case R.id.pay_start:
                Log.e("=====", "pay_start");
                OrderListBean orderListBeans = (OrderListBean) v.getTag();
                Log.e("=====getORDER_ID()", orderListBeans.getORDER_ID());
                Log.e("=====getORDER_NAME()", orderListBeans.getORDER_NAME());
                Log.e("=====getORDER_MONEY()", orderListBeans.getORDER_MONEY());
                AppUtil.startPayment(getActivity(),orderListBeans.getORDER_ID(), orderListBeans.getORDER_NAME(), orderListBeans.getORDER_MONEY());
                break;
        }
    }

    private void cancelOrder(final String order_id) {
        CancelOrderApi api = new CancelOrderApi(order_id);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if (null != resp) {
                    if (resp.isOk()) {
                        Toast.makeText(getActivity(), "订单删除成功", Toast.LENGTH_LONG).show();
                        //取消闹钟
                        AlarmUtil.cancelAlarm(mActivity, IntentConstants.Action.orderRemind, Integer.parseInt(order_id));

                        EventBus.getDefault().post(new OrderStateChangeEvent());
                    } else {
                        Toast.makeText(getActivity(), resp.message, Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }
    public void onEvent(OrderStateChangeEvent event){
        if(event!=null){
            loadData();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
